// pages/goods_detail/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageList: [],
    swlist: [],
    isflag: false
  },
  goods_id: 0, // 商品的Id值
  goodsInfo: {}, // 商品的详情

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    this.goods_id = options.goods_id
    this.getdata()
  },

  //获取基本数据
  getdata: async function () {
    let {
      data
    } = await wx.gooddetailApi.gooddetaildata({
      goods_id: this.goods_id
    })
    console.log(data);
    this.goodsInfo = data.message
    let arr = data.message.pics
    this.setData({
      pageList: data.message,
      swlist: arr
    })
    console.log(this.data.swlist);


  },

  //点击加购
  cartAdd: function () {
    let cartdata = wx.getStorageSync('cartdata') || []; //同步获取本地数据

    //判断购物车中是否存在相同数据-id
    let index = cartdata.findIndex(item => item.goods_id === this.goodsInfo.goods_id)
    if (index === -1) {
      //如果购物车中没有当前数据 
      this.goodsInfo.num = 1;
      this.goodsInfo.checked = true;
      cartdata.push(this.goodsInfo);

    } else { //如果购物车中存在当前商品
      cartdata[index].num++;
    }
    wx.setStorageSync('cartdata', cartdata);
    //弹出提示框
    wx.showToast({
      title: '加入购物车成功',
      icon: 'success',
      mask: true //遮罩层
    })

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //全局函数  获取包含当前页面的所有页面调用栈
    let pages = getCurrentPages();
    //通过页面调用栈函数获取当前页的vt
    let currentPage = pages[pages.length - 1];
    //通过当前页面的对象vt获取当页面上的页面参数 options
    let arrid = currentPage.options;

    //收藏前置逻辑
    let collect = wx.getStorageSync('collect') || []
    let index = collect.findIndex(item => item.goods_id === this.goodsInfo.goods_id)
    if (index !== -1) {
      this.setData({
        isflag: true
      })
    }
  },

  //点击收藏
  clickCollect: function (e) {
    let isflag
    let collect = wx.getStorageSync('collect') || [] //空
    let index = collect.findIndex(item => item.goods_id === this.goodsInfo.goods_id) //查找一下是否被收藏
    if (index !== -1) {
      isflag = false
      collect.splice(index, 1)
      wx.showToast({
        title: '移出收藏成功',
      })
    } else {
      isflag = true;
      collect.push(this.goodsInfo)
      wx.showToast({
        title: '添加收藏成功',
      })

    }
    this.setData({
      isflag
    })
    wx.setStorageSync('collect', collect)
  },


})